package com.hashcoding.eyes.ui.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.Window;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.hashcoding.eyes.R;
import com.hashcoding.eyes.ui.protocol.ILifecycleListener;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * BaseActivity
 *
 * @author Maochuan
 * @date 2016-02-03
 */
public abstract class BaseActivity extends AppCompatActivity {
    private MaterialDialog mProgressDialog;
    private Toast mToast;

    private ILifecycleListener mLifeListener;

    protected LayoutInflater mInflater;

    private boolean mDestroyed = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDestroyed = false;
        mInflater = getLayoutInflater();
        setOverflowShowingAlways();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (mLifeListener != null) {
            mLifeListener.onActivityResult(requestCode, resultCode, data);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;

            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if (featureId == Window.FEATURE_ACTION_BAR && menu != null) {
            if ("MenuBuilder".equals(menu.getClass().getSimpleName())) {
                try {
                    Method method = menu.getClass().getDeclaredMethod("setOptionalIconsVisible",
                            Boolean.TYPE);
                    method.setAccessible(true);
                    method.invoke(menu, true);
                } catch (Exception e) {
                    // ignore
                }
            }
        }
        return super.onMenuOpened(featureId, menu);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            onBackPressed();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        // 返回默认结束当前页面
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        mDestroyed = true;
        super.onDestroy();
    }

    @Override
    public boolean isDestroyed() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            return mDestroyed || super.isDestroyed();
        } else {
            return mDestroyed;
        }
    }

    /**
     * Set action bar overflow showing always, avoid it's not showing on some phones.
     */
    private void setOverflowShowingAlways() {
        try {
            ViewConfiguration config = ViewConfiguration.get(this);
            Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
            menuKeyField.setAccessible(true);
            menuKeyField.setBoolean(config, false);
        } catch (Exception e) {
            // ignore
        }
    }

    protected boolean canShowDialog() {
        return !(isDestroyed() || isFinishing());
    }

    protected View inflateView(int resId) {
        return mInflater.inflate(resId, null);
    }

    public void shortToast(int resId) {
        shortToast(getString(resId));
    }

    public void shortToast(String content) {
        if (mToast != null) {
            mToast.setText(content);
            mToast.setDuration(Toast.LENGTH_SHORT);
        } else {
            mToast = Toast.makeText(this, content, Toast.LENGTH_SHORT);
        }
        mToast.show();
    }

    public void showProgressDialog(int resId, boolean cancelAble) {
        showProgressDialog(getString(resId), cancelAble);
    }

    public void showProgressDialog(String message, boolean cancelAble) {
        if (TextUtils.isEmpty(message) || !canShowDialog()) {
            return;
        }

        if (null == mProgressDialog) {
            mProgressDialog = new MaterialDialog.Builder(this)
                    .progress(true, 0)
                    .widgetColorRes(android.R.color.holo_red_light)
                    .build();
            mProgressDialog.setCanceledOnTouchOutside(false);
        }

        mProgressDialog.setContent(message);
        mProgressDialog.setCancelable(cancelAble);
        mProgressDialog.show();
    }

    public void dismissProgressDialog() {
        if (null != mProgressDialog && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    public void showMessageDialog(int message) {
        showMessageDialog(getString(message));
    }

    public void showMessageDialog(String message) {
        if (canShowDialog()) {
            new MaterialDialog.Builder(this)
                    .title(R.string.tip)
                    .content(message)
                    .cancelable(true)
                    .positiveText(R.string.ok)
                    .negativeText(R.string.cancel)
                    .onNegative(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction action) {
                            dialog.dismiss();
                        }
                    })
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction action) {
                            dialog.dismiss();
                        }
                    })
                    .show();
        }
    }

    public void setLifecycleListener(ILifecycleListener lifeListener) {
        mLifeListener = lifeListener;
    }

}



